// downloadImage.js
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

async function downloadImage(url, newsId) {
  try {
    const timestamp = Date.now();
    const hash = crypto.createHash('md5').update(url).digest('hex').slice(0, 8);
    const filename = `${newsId}_${timestamp}_${hash}.jpg`;
    const filepath = path.join(__dirname, 'images', filename);

    const response = await axios.get(url, { responseType: 'stream' });
    await fs.promises.mkdir(path.dirname(filepath), { recursive: true });

    const writer = fs.createWriteStream(filepath);
    response.data.pipe(writer);

    return new Promise((resolve, reject) => {
      writer.on('finish', () => resolve(filename));
      writer.on('error', reject);
    });
  } catch (err) {
    console.error('图片下载失败:', url);
    return null;
  }
}

module.exports = downloadImage;
